# -*- coding: utf-8 -*-
"""
    moe.users.handlers
    ~~~~~~~~~~~~~~~~~~

    Users handlers.

    :copyright: 2009 by tipfy.org.
    :license: BSD, see LICENSE.txt for more details.
"""
from google.appengine.api import users

from werkzeug import cached_property

from tipfy import RequestHandler
from tipfy.auth import login_required
from tipfy.i18n import _, lazy_gettext

from moe.handlers import BaseHandler, LoginRequiredHandler
from moe.users.forms import SignupForm
from moe.models import User


class BaseUsersHandler(BaseHandler):
    """Base class for the users app."""
    def __init__(self, app, request):
        BaseHandler.__init__(self, app, request)

        self.breadcrumbs.add(lazy_gettext('Home'), 'home/index')
        self.breadcrumbs.add(lazy_gettext('Users'), 'users/index')


class LoginHandler(BaseHandler):
    def get(self, **kwargs):
        if self.auth.user:
            return self.redirect('/')

        redirect = self.request.args.get('redirect', '/')
        return self.redirect(users.create_login_url(redirect))


class LogoutHandler(BaseHandler):
    def get(self, **kwargs):
        if not self.auth.user:
            return self.redirect('/')

        redirect = self.request.args.get('redirect', '/')
        return self.redirect(users.create_logout_url(redirect))


class SignupHandler(LoginRequiredHandler):
    def get(self, **kwargs):
        redirect_url = self.redirect_path()

        if self.auth.user:
            # User is already registered, so don't display the signup form.
            return self.redirect('/')

        return self.render_response('users/signup.html', form=self.form)

    def post(self, **kwargs):
        redirect_url = self.redirect_path()

        if self.auth.user:
            # User is already registered, so don't process the signup form.
            return self.redirect(redirect_url)

        if self.form.validate():
            auth_id = 'gae|%s' % self.auth.session.user_id()
            user = self.auth.create_user(self.form.nickname.data, auth_id,
                email=self.auth.session.email())
            if user:
                self.add_message('success', 'You are now registered. '
                    'Welcome!', flash=True, life=5)
                return self.redirect(redirect_url)
            else:
                self.add_message('error', 'This nickname is already '
                    'registered.', life=None)
                return self.get(**kwargs)

        self.add_message('error', 'A problem occurred. Please correct the '
            'errors listed in the form.', life=None)
        return self.get(**kwargs)

    @cached_property
    def form(self):
        return SignupForm(self.request)

    def redirect_path(self, default='/'):
        url = self.request.args.get('continue', '/')

        if not url.startswith('/'):
            url = default

        return url


class UserProfileHandler(BaseUsersHandler):
    def get(self, **kwargs):
        self.breadcrumbs.add(self.user_entity.username, 'users/profile',
            username=self.user_entity.username)

        context = {
            'user': self.user_entity,
        }
        return self.render_response('users/profile.html', **context)

    @cached_property
    def user_entity(self):
        username = self.request.rule_args.get('username')
        if username is not None:
            entity = User.get_by_username(username)
            if not entity:
                self.abort(404)

            return entity


class UserListHandler(BaseUsersHandler):
    def get(self, **kwargs):
        context = {
        }
        return self.render_response('users/user_list.html', **context)


class UserFavoriteHandler(BaseUsersHandler):
    """Adds or removes a favorite."""
    def post(self, **kwargs):
        #raise ValueError();
        return 'weee'

        if not self.auth.user:
            self.abort(403)

        action = self.request.form.get('action')
        if action not in ('add', 'delete'):
            self.abort(403)

        favorite_key = self.request.form.get('favorite_key')
        if not favorite_key:
            self.abort(403)

        user_key = str(self.auth.user.key())
        if action == 'add':
            res = UserFavorites.add_favorite(user_key, favorite_key)
        else:
            res = UserFavorites.delete_favorite(user_key, favorite_key)

        return ''

    get = post


class EditProfileHandler(BaseUsersHandler):
    def get(self, **kwargs):
        context = {
        }
        return self.render_response('users/profile_edit.html', **context)

    def post(self, **kwargs):
        return self.get(**kwargs)
